package thread;

import java.util.PriorityQueue;
import java.util.Timer;

/**
 * @Author liangzai
 * @Description:
 */

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    private long time;

    public MyTimerTask(Runnable runnable,long time){
        this.time = time;
        this.runnable = runnable;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }
}

class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>(1000);
    private Object locker = new Object();

    public MyTimer(){
        Thread t = new Thread(()->{
            while (true) {
                synchronized (locker){
                    try{
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        long time = queue.peek().getTime();
                        if (time > System.currentTimeMillis()) {
                            locker.wait(time-System.currentTimeMillis());
                            continue;
                        }else {
                            queue.poll().getRunnable().run();
                        }
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable ,long time){
        synchronized (locker){
            MyTimerTask task = new MyTimerTask(runnable,time+System.currentTimeMillis());
            queue.offer(task);
            locker.notify();
        }
    }
}

public class Demo1 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(()->{
            System.out.println("hello 3000!");
        },3000);
        timer.schedule(()->{
            System.out.println("hello 2000!");
        },2000);
        timer.schedule(()->{
            System.out.println("hello 1000!");
        },1000);
    }
}











